/**
 * 
 */
package PDFd.ClientLibrary;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import android.util.Log;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.InvalidMessageContentsException;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageResult;

/**
* <p>Title: RenderEngine</p>
* <p>Description: A class that implements IRenderEngine
* renders an image from the following URL sites. </p>
* @author Matt, Tom, Andrew, Kong
* @email matt.mckay@my.uwrf.edu,tom.florin@my.uwrf.edu,
* andrew.kathan@my.uwrf.edu,kong.xiong-1@my.uwrf.edu
* @date December 1st,2011*/
public class RenderEngine implements IRenderEngine {

	private static final String LOG_TAG = "RenderEngine";

    private AmazonS3Client s3Client = null;
    private AmazonSQSClient sqsClient = null;
    private String pdfbucket = "bucket.pdf";
    private String pngbucket = "bucket.png";
    private String sqspdf = "https://queue.amazonaws.com/277957951592/sqspdf";
    private  String sqspng = "https://queue.amazonaws.com/277957951592/sqspng";

    
	/** 
	 * @see PDFd.ClientLibrary.IRenderEngine#addPDF(byte[])
	 */
	@Override
	public String addPDF(byte[] f) {
		validateCredentials();
		Log.i(LOG_TAG,"Amazon Credentials Authorized");
		UUID uuid = UUID.randomUUID();
		try{
		InputStream stream = new ByteArrayInputStream(f);
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(f.length);
		meta.setContentType("application/pdf");
		s3Client.putObject(pdfbucket,uuid.toString(),stream,meta);
		Log.i(LOG_TAG,"PDF uploaded to bucket");
		s3Client.setObjectAcl(pdfbucket,uuid.toString(),CannedAccessControlList.PublicRead);
		SendMessageResult messageresult = sqsClient.sendMessage(new SendMessageRequest(sqspdf,uuid.toString()));
		Log.i(LOG_TAG,"Message sent to Queue: "+messageresult.toString());
		}catch(InvalidMessageContentsException imce){
			Log.i(LOG_TAG,"Error in addPDF: Invalid Message Content Exception :"+imce.getMessage());
		}catch(AmazonS3Exception as3e){
			Log.i(LOG_TAG, "Error at getAsPNG: S3 Exception: "+as3e.getMessage());
		}
		catch(AmazonServiceException ase){
			Log.i(LOG_TAG,"Error at getAsPNG: Amazon Service Exception: "+ ase.getMessage());
		}
		catch(AmazonClientException ace){
			Log.i(LOG_TAG,"Error at getAsPNG: Client Exception: "+ace.getMessage());
		}
		catch(Exception ex){
			Log.i(LOG_TAG, "Error at getAsPNG: Generic Error: "+ex.getMessage());
		}
		return uuid.toString();
	}

	/** 
	 * @see PDFd.ClientLibrary.IRenderEngine#getAsPNG(java.lang.String)
	 */
	@Override
	public byte[] getAsPNG(String uuid, int duration) {
		validateCredentials();
		Log.i(LOG_TAG,"Amazon Credentials Authorized");
		byte[] file = null;
		try{
			int count = 0;
			while(!CheckSQSForFinishedFile(uuid) && count < duration){
				Thread.sleep(3000);
				count++;
			}
			S3Object object = s3Client.getObject(new GetObjectRequest(pngbucket,uuid));
			Log.i(LOG_TAG, "byte array returned from s3 successifly");
			
			ByteArrayOutputStream buffer = new ByteArrayOutputStream();
			int nRead;
			byte[] data = new byte[16384];
			while ((nRead = object.getObjectContent().read(data, 0, data.length)) != -1) {
			  buffer.write(data, 0, nRead);
			}
			buffer.flush();
			file = buffer.toByteArray();
			
			
		}
		catch(AmazonS3Exception as3e){
			Log.i(LOG_TAG, "Error at getAsPNG: S3 Exception: "+as3e.getMessage());
		}
		catch(AmazonServiceException ase){
			Log.i(LOG_TAG,"Error at getAsPNG: Amazon Service Exception: "+ ase.getMessage());
		}
		catch(AmazonClientException ace){
			Log.i(LOG_TAG,"Error at getAsPNG: Client Exception: "+ace.getMessage());
		}
		catch(Exception ex){
			Log.i(LOG_TAG, "Error at getAsPNG: Generic Error: "+ex.getMessage());
		}
		return file;
	}

	/** 
	 * @see PDFd.ClientLibrary.IRenderEngine#getAsPDF(java.lang.String, java.io.File)
	 */
	@Override
	public byte[] getAsPDF(String uuid,byte[] overlayPNG) {
		validateCredentials();
		return null;
	}
	/**
	 * Checks if the file is finished 
	 * @param uuid
	 * @return true
	 */
	private boolean CheckSQSForFinishedFile(String uuid){
		
		@SuppressWarnings("unchecked")
		List<Message> messages = sqsClient.receiveMessage(new ReceiveMessageRequest(sqspng)).getMessages();
		for(Message message:messages){
			if(message.getBody().equals(uuid)){
				sqsClient.deleteMessage(new DeleteMessageRequest(sqspng,message.getReceiptHandle()));
				return true;
			}
		}
		return false;
		
	}
	/**
	 * Creates a new client if they don't have the creditantials.
	 */
	private void validateCredentials() {
        if ( s3Client == null || sqsClient == null ) {        
            Log.i( LOG_TAG, "Creating New Clients." );
        
            AWSCredentials credentials = new BasicAWSCredentials("AKIAI5YS3IFJOL7NC3GQ", "Zqr6JH61JDbsw3qfwArkkRzKY0HirmIBt/XXdrCu");
		    s3Client = new AmazonS3Client( credentials );
		    sqsClient = new AmazonSQSClient( credentials );
        }
    }
}
